<?php
// +----------------------------------------------------------------------
// | Longbing [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright Chengdu longbing Technology Co., Ltd.
// +----------------------------------------------------------------------
// | Website http://longbing.org/
// +----------------------------------------------------------------------
// | Sales manager: +86-13558882532 / +86-13330887474
// | Technical support: +86-15680635005
// | After-sale service: +86-17361005938
// +----------------------------------------------------------------------
namespace app\shortvideo\controller;

use app\activity\info\PermissionActivity;
use app\AdminRest;
use app\appoint\info\PermissionAppoint;
use app\house\info\PermissionHouse;
use app\shop\model\AdminGoods;
use app\shop\model\AdminShopSpePrice;
use app\shortvideo\model\AdminCompany;
use app\shortvideo\model\Shortvideo;
use app\shortvideo\model\ShortvideoCompany;
use app\shortvideo\model\ShortvideoGoods;
use app\shortvideo\model\ShortvideoPreferential;
use think\App;
use think\facade\Db;
use app\shop\info\PermissionShop; #判断商城权限
use app\passenger\info\PermissionPassenger; #判断带客有礼权限
use app\redbag\info\PermissionRedbag; #新客福包 权限  需商城权限
use app\reduction\info\PermissionReduction; #满减返佣 权限 需商城权限
use app\shortvideo\validate\ShortvideoValidate as videoValidate; #验证器

class Admin extends AdminRest{
    protected $model;
    protected $shortvideo_company_model; #短视频关联公司
    protected $shortvideo_goods_model; #短视频关联商品
    protected $company_model; #公司表
    protected $goods_model;
    protected $shortvideo_preferential_model; #关联优惠

    protected $page_size;

    public function __construct(App $app) {
        $this->app = $app;
        parent::__construct($app);
        $this->model = new Shortvideo();
        $this->shortvideo_company_model = new ShortvideoCompany();
        $this->shortvideo_goods_model = new ShortvideoGoods();
        $this->company_model = new AdminCompany();
        $this->goods_model = new AdminGoods();

        $this->shortvideo_preferential_model = new ShortvideoPreferential();

        $this->page_size = isset($this->_param['limit'])?$this->_param['limit']:10;
    }

    /**
     **@author lichuanming
     * @DataTime: 2020/5/19 11:33
     * @功能说明: 基本配置 判断是否拥有商城权限
     */
    public function config(){
        $shopPer = new PermissionShop($this->_uniacid,'');

        $shop = ($shopPer->sAuth() && $shopPer->pAuth())?true:false;

        $spe_price_model = new AdminShopSpePrice();

        $list = [];
        if($shop){

            $where[] = ['uniacid','=',$this->_uniacid];

            $where[] = ['status','=',1];

            $where[] = ['is_member','=',0];

            if(isset($this->_param['name'])){
                $where[] = ['name','like',"%{$this->_param['name']}%"];
            }

            $list = $this->goods_model->goodList($where,$this->page_size); //获取商品列表

            if(!empty($list['data'])){

                foreach ($list['data'] as &$v){
                    //总库存
                    $v['stock'] = $spe_price_model->getGoodsStock($v['id']);


                }
            }
        }
        $config = [
            'shop' => $shop, #判断是否拥有商城权限

            'goods_list' => $list,
        ];
        return $this->success($config);
    }






    /**
     **@author lichuanming
     * @DataTime: 2020/5/20 14:49
     * @功能说明: 优惠信息
     */
    public function discount(){
        $shopPer = new PermissionShop($this->_uniacid,'');

        $passengerPer = new PermissionPassenger($this->_uniacid,'');

        $redbagPer = new PermissionRedbag($this->_uniacid,'');

        $reductionPer = new PermissionReduction($this->_uniacid,'');


        $shop      = ($shopPer->sAuth() && $shopPer->pAuth())?true:false; #判断商城权限
        $passen    = ($passengerPer->sAuth() && $passengerPer->pAuth())?true:false; #判断断带客有礼权限
        $redbag    = ($redbagPer->sAuth() && $redbagPer->pAuth())?true:false; #判断新客福包权限
        $reduction = ($reductionPer->sAuth() && $reductionPer->pAuth())?true:false; #满减返佣权限


        $resData = [];
        if($passen){
            $resData[] = array(
//                'api_path' => '/passenger/admin/AdminActive/activeList',
                'api_path' => '/shortvideo/admin/passenger/activeList',
                'type' => 1,
                'title' => '带客有礼',
            );
        }

        if($shop && $redbag){
            $resData[] = array(
//                'api_path' => '/redbag/admin/AdminActive/activeList',
                'api_path' => '/shortvideo/admin/redbag/activeList',
                'type' => 2,
                'title' => '新客福包',
            );
        }

        if($shop && $reduction){
            $resData[] = array(
//                'api_path' => '/reduction/admin/AdminActive/activeList',
                'api_path' => '/shortvideo/admin/reduction/activeList',
                'type' => 3,
                'title' => '满减返佣',
            );
        }

        return $this->success($resData);
    }


    /**
     **@author lichuanming
     * @DataTime: 2020/5/18 13:59
     * @功能说明: 视频文件列表
     */
    public function index(){
        $where = [];
        if(isset($this->_param['title'])){
            $name = $this->_param['title'];
            $where[] = ['title','like',"%{$name}%"];
        }
        $where[] = ['uniacid','=',$this->_uniacid];
        $list = $this->model->videoList($where,$this->page_size);
        return $this->success($list);
    }

    /**
     **@author lichuanming
     * @DataTime: 2020/5/19 9:00
     * @功能说明: 修改短视频状态
     */
    public function videoStatus(){
        $data = $this->_input;
        if(isset($data['status']) && isset($data['id'])){
            $status = $data['status'];
            $res = $this->model->videoUpdate(['id'=>$data['id'],'uniacid'=>$this->_uniacid],['status'=>$status]);
            return $this->success($res);
        }
        return $this->error('参数错误！');
    }

    /**
     **@author lichuanming
     * @DataTime: 2020/5/18 14:00
     * @功能说明: 添加视频
     */
    public function addvideo(){
        $input = $this->_input;
        #参数验证 --
        $validate = new videoValidate();

        $result = $validate->scene('add')->check($input);

        if (!$result) {

            return $this->error($validate->getError());
        }
        $data = $this->model->returnData($input);

        $data['uniacid'] = $this->_uniacid;

        Db::startTrans();

        $all_company = $input['all_company'];

        $video_id = $this->model->videoAdd($data);
        //公司员工限制
        if(!$all_company){

            $limit_type = !empty($input['limit_type'])?$input['limit_type']:0;
            //公司
            if($limit_type==0){

                $target_id = $this->shortvideo_company_model->changeData($input['company']);

            }else{
                //员工
                $target_id = $input['staff'];
            }
            $this->companyVideoAdd($target_id,$video_id,$limit_type);
        }
        //判断是否是全选商品
        if(isset($input['goods'])){

            $this->goodsVideoAdd($input['goods'],$video_id);
        }
        if(isset($input['preferential_id']) && isset($input['preferential_type'])){

            if($input['preferential_id'] > 0 && $input['preferential_type'] > 0){

                $this->preferentialVideoAdd([$input['preferential_id']],$video_id,$input['preferential_type']);
            }
        }

        Db::commit();
        return $this->success([]);
    }

    /**
     **@author lichuanming
     * @DataTime: 2020/5/18 14:01
     * @功能说明: 修改视频信息
     */
    public function updateVideo(){
        $input= $this->_input;
        $id = $input['id'];

        if(count($input)>2){
            #验证器--
            $validate = new videoValidate();
            $result = $validate->scene('edit')->check($input);
            if (!$result) {
                return $this->error($validate->getError());
            }

            $where[] = ['id','=',$id];
            $all_company = $input['all_company'];
            Db::startTrans();
            $data = $this->model->returnData($input);
            $res  = $this->model->videoUpdate($where,$data);
            //判断是否是全选商品
            if(!$all_company){

                $limit_type = !empty($input['limit_type'])?$input['limit_type']:0;
                //公司
                if($limit_type==0){

                    $target_id = $this->shortvideo_company_model->changeData($input['company']);

                }else{
                    //员工
                    $target_id = $input['staff'];
                }

                $this->companyVideoAdd($target_id,$id,$limit_type);
            }
            if(isset($input['goods'])){

                $this->goodsVideoAdd($input['goods'],$id);
            }
            if(isset($input['preferential_id']) && isset($input['preferential_type'])){
                $this->preferentialVideoAdd([$input['preferential_id']],$id,$input['preferential_type']);
            }
            Db::commit();
        }else{
            $data = $this->model->where('id',$id)->find();
            $res['info'] = !empty($data)?$data->toArray():$data;
            $res['info']['all_company'] = $data['is_public'];
            #获取视频关联的公司信息
            if($data['is_public']==1){ #是否公共视频
//                $res['company'] = $this->shortvideo_company_model->getCompanyIds([
//                    'uniacid' => $this->_uniacid,
//                    'status'  => 1,
//                ]);

                $res['company'] = [];
            }else{

                if($data['limit_type']==0){

                    $res['company'] = $this->shortvideo_company_model->getId([
                        'a.uniacid' => $this->_uniacid,
                        'a.video_id'=> $this->_input['id'],
                        'a.status'  => 1,
                        'b.status'  => 1,
                    ]);

                }else{

                    $res['staff'] = $this->shortvideo_company_model->getStaffId($data['id']);

                }

            }
            
            #获取视频关联的商品信息
            $res['goods'] = $this->shortvideo_goods_model->getId([
                'a.uniacid' => $this->_uniacid,
                'a.video_id'=> $this->_input['id'],
                'a.status'  => 1,
                'b.status'  => 1,
            ]);
            $res['goods_list'] = $this->goods_model->where('id','in',$res['goods'])->field('id,name,cover,type,uniacid')->select();

            #获取视频关联的优惠信息
            $preferential = $this->shortvideo_preferential_model->getId([
                'uniacid' => $this->_uniacid,
                'video_id' => $id
            ]);
            if(!empty($preferential)){ //目前只支持关联一个
                $res['info']['preferential_id'] = $preferential[0]['id'];
                $res['info']['preferential_type'] = $preferential[0]['type'];
                $res['info']['preferential_info'] = $preferential[0]['info'];
            }
        }
        return $this->success($res);
    }

    /**
     * @param $data
     * @param $video_id
     * 添加shortvideo_company
     */
    public function companyVideoAdd($data,$video_id,$limit_type=0){

        $this->shortvideo_company_model->where(['uniacid'=>$this->_uniacid,'video_id'=>$video_id])->delete();

        if(!empty($data)){

            foreach ($data as $k=>$v){

                $insert[$k]['uniacid']  = $this->_uniacid;

                $insert[$k]['video_id'] = $video_id;

                $insert[$k]['company_id'] = $limit_type==0?$v:0;

                $insert[$k]['staff_id']   = $limit_type==1?$v:0;

                $insert[$k]['create_time'] = time();

                $insert[$k]['update_time'] = time();

                $insert[$k]['status']      = 1;

            }

            $res = $this->shortvideo_company_model->saveAll($insert);
        }

        return !empty($res)?$res:1;
    }



    public function goodsVideoAdd($data,$video_id){
        $this->shortvideo_goods_model->goodsVideoDel(['uniacid'=>$this->_uniacid,'video_id'=>$video_id],$data);
        foreach ($data as $v){
            $com = $this->shortvideo_goods_model->goodsVideoFind(['video_id'=>$video_id,'status'=>1,'goods_id'=>$v,'uniacid'=>$this->_uniacid]);
            if(empty($com)){
                $res = $this->shortvideo_goods_model->goodsVideoAdd(['uniacid'=>$this->_uniacid,'video_id'=>$video_id,'goods_id'=>$v]);
            }
        }
        return !empty($res)?$res:1;
    }

    public function preferentialVideoAdd($data,$video_id,$type){
        $this->shortvideo_preferential_model
            ->preferentialVideoDel(['uniacid'=>$this->_uniacid,'video_id'=>$video_id],$data);
        foreach ($data as $v){
            $com = $this->shortvideo_preferential_model
                ->preferentialVideoFind(['video_id'=>$video_id,'preferential_id'=>$v,'uniacid'=>$this->_uniacid]);
            if(empty($com)){
                $res = $this->shortvideo_preferential_model
                    ->preferentialVideoAdd(['uniacid'=>$this->_uniacid,'video_id'=>$video_id,'preferential_id'=>$v,'type'=>$type]);
            }
        }
        return !empty($res)?$res:1;
    }

    /**
     **@author lichuanming
     * @DataTime: 2020/5/19 9:30
     * @功能说明:公司列表
     */
    public function company(){
        $where[] = ['uniacid','=',$this->_uniacid];
        $where[] = ['status' ,'=',1];
        $list = $this->company_model->companySelect($where);
        return $this->success($list);
    }
}